package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.exception.BaseException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.RandomGenerator;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.sql.SqlUtil;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.OrderPayType;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.vo.OrderPayTypeResVo;
import com.qujia.station.domain.vo.StationByEnterpriseVo;
import com.qujia.station.mapper.OrderPayTypeMapper;
import com.qujia.station.mapper.PayOrderMapper;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.OrderPayTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

@Service("orderPayTypeService")
@Slf4j
public class OrderPayTypeServiceImpl implements OrderPayTypeService {

    @Autowired
    private OrderPayTypeMapper orderPayTypeMapper;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Override
    public List<OrderPayType> selectOrderPayTypeName(OrderPayType orderPayType) {
        List<OrderPayType> orderPayTypeList = orderPayTypeMapper.selectOrderPayType(orderPayType);
        return orderPayTypeList;
    }

    @Override
    public List<OrderPayType> selectOrderPayTypeList(OrderPayType orderPayType) {
        OrderPayType orderPay = new OrderPayType();
        BeanUtils.copyProperties(orderPayType,orderPay);
        orderPay.setPageNum(null);
        orderPay.setPageSize(null);
        orderPay.setIsDeleted("0");
        log.info("selectOrderPayTypeList:[{}]", JSONObject.toJSONString(orderPay));
        List<OrderPayType> orderPayTypeList = orderPayTypeMapper.selectOrderPayType(orderPay);
        log.info("selectOrderPayTypeList:[{}]",orderPayTypeList.size());
        List<OrderPayType> newOrderPayTypeList = new ArrayList<>();
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"wxAzfb", "移动支付（微信支付宝）"));
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"pos", "聚合支付（微信支付宝）"));
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"yhk", "银行卡"));
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"dzk", "会员卡"));
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"dkq", "实体卡"));
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"cdk", "车队卡"));
        newOrderPayTypeList.add(getOrderPayType(orderPayType,"xj", "现金"));
        for (OrderPayType payType : orderPayTypeList) {
            String time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, payType.getCreateTime());
            payType.setAddTime(time);
            newOrderPayTypeList.add(payType);
        }
        return newOrderPayTypeList;
    }

    private OrderPayType getOrderPayType(OrderPayType orderPayType, String payType, String payTypeName){
        OrderPayType newOrderPayType = new OrderPayType();
        if(Objects.nonNull(orderPayType) && Objects.nonNull(orderPayType.getEnterpriseId())){
            Enterprise enterprise = enterpriseService.selectEnterpriseById(orderPayType.getEnterpriseId());
            newOrderPayType.setEnterpriseName(Objects.nonNull(enterprise) ? enterprise.getEnterpriseName() : "-");

        }else if(Objects.nonNull(orderPayType) && Objects.nonNull(orderPayType.getStationId())){
            Enterprise enterprise = enterpriseService.selectEnterpriseByStationId(orderPayType.getStationId());
            orderPayType.setEnterpriseId(Objects.nonNull(enterprise) ? enterprise.getEnterpriseId() : null);
            orderPayType.setEnterpriseName(Objects.nonNull(enterprise) ? enterprise.getEnterpriseName() : "-");
        }
        newOrderPayType.setStationName("-");
        newOrderPayType.setAddTime("-");
        newOrderPayType.setPayType(payType);
        newOrderPayType.setPayTypeName(payTypeName);
        newOrderPayType.setIsEdit("1");
        newOrderPayType.setIsDeleted("0");
        return newOrderPayType;
    }


    @Override
    public int saveOrderPayType(OrderPayType orderPayType) {
        if(Objects.isNull(orderPayType) || StringUtils.isEmpty(orderPayType.getPayTypeName())
                || Objects.isNull(orderPayType.getStationId())){
            throw new BaseException("请求参数异常");
        }
//        OrderPayType payTypeName = orderPayTypeMapper.selectOrderPayTypeByPayType(orderPayType);
//        if(Objects.nonNull(payTypeName)){
//            throw new BaseException("支付方式名称已存在");
//        }

        // 生成支付方式标识
        String time = DateUtils.parseDateToStr(DateUtils.YYYYMMDD,new Date());
        String payType = time + RandomGenerator.generateRandomString(5);
        OrderPayType newPayType = new OrderPayType();
        newPayType.setStationId(orderPayType.getStationId());
        newPayType.setPayType(payType);
        OrderPayType oldPayType = orderPayTypeMapper.selectOrderPayTypeByPayType(newPayType);
        if(Objects.nonNull(oldPayType)){
            throw new BaseException("请重新请求");
        }
        orderPayType.setPayType(payType);
        // 获取油企油站
        if(Objects.nonNull(orderPayType.getStationId())){
            Station station = stationService.selectStationById(orderPayType.getStationId());
            if(Objects.isNull(station)){
                throw new BaseException("油站不存在");
            }
            orderPayType.setStationName(station.getStationName());
            Enterprise enterprise = enterpriseService.selectEnterpriseByStationId(orderPayType.getStationId());
            if(Objects.isNull(enterprise)){
                throw new BaseException("油站不存在");
            }
            orderPayType.setEnterpriseId(enterprise.getEnterpriseId());
            orderPayType.setEnterpriseName(enterprise.getEnterpriseName());
        }
        return orderPayTypeMapper.insertSelective(orderPayType);
    }



    @Override
    public int updateOrderPayType(OrderPayType orderPayType) {
        if(Objects.nonNull(orderPayType) && Objects.nonNull(orderPayType.getStationId())){
            Station station = stationService.selectStationById(orderPayType.getStationId());
            if(Objects.isNull(station)){
                throw new BaseException("油站不存在");
            }
            orderPayType.setStationName(station.getStationName());

            OrderPayType payType = orderPayTypeMapper.selectByPrimaryKey(orderPayType.getId());
            if (null != payType && !orderPayType.getPayTypeName().equals(payType.getPayTypeName())) { //名称未变化，无需处理
                //未该名称之前，是否有被使用过（订单表是否存在该支付方式的数据）
                if (payOrderMapper.countPayOderNumByPayType(payType.getPayType()) > 0){
                    //有，备份标记 0未删除 1已删除 2支付方式被使用过并且有订单数据，被改名了
                    payType.setIsDeleted("2");
                    payType.setUpdateTime(new Date());
                    orderPayTypeMapper.updateByPrimaryKey(payType);

                    //需要按原有的数据生成一条新的数据
                    payType.setId(null);
                    payType.setIsDeleted("0");
                    payType.setStationId(station.getStationId());
                    payType.setStationName(station.getStationName());
                    // 生成支付方式标识
                    String time = DateUtils.parseDateToStr(DateUtils.YYYYMMDD,new Date());
                    String payTypeCode = time + RandomGenerator.generateRandomString(5);
                    payType.setPayType(payTypeCode);
                    payType.setPayTypeName(orderPayType.getPayTypeName());
                    return orderPayTypeMapper.insertSelective(payType);
                }
            }
        }
//        OrderPayType oldPayType = orderPayTypeMapper.selectByPrimaryKey(orderPayType.getId());
//        OrderPayType payType = new OrderPayType();
//        payType.setStationId(oldPayType.getStationId());
//        payType.setPayTypeName(orderPayType.getPayTypeName());
//        OrderPayType result = orderPayTypeMapper.selectOrderPayTypeByPayType(payType);
//        if(Objects.nonNull(result)){
//            throw new BaseException("支付方式名称已存在");
//        }
        return orderPayTypeMapper.updateByPrimaryKeySelective(orderPayType);
    }

    @Override
    public int deleteOrderPayType(Long id) {
        return orderPayTypeMapper.updateById(id);
    }

    @Override
    public List<OrderPayTypeResVo> queryOrderPayTypeList(String payTypeName) {
        // 获取当前登录的用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        OrderPayType payType = new OrderPayType();
        List<String> stationIds = null;
        if (UserConstants.LEVEL_TWO.equals(sysUser.getLevelId())) {//油企
            payType.setEnterpriseId(sysUser.getEnterpriseId());
            List<Station> stations = stationService.selectStationListByEnterpriseId(sysUser.getEnterpriseId());
            if (null != stations) {
                stationIds = stations.stream().map(x -> x.getStationId() + "").collect(Collectors.toList());
            }
        }
        if (UserConstants.LEVEL_FIVE.equals(sysUser.getUserLevel()) || UserConstants.LEVEL_SIX.equals(sysUser.getUserLevel())) {
            //区域经理和业务员
            List<StationByEnterpriseVo> stationByEnterprise = stationService.getStationByEnterprise(null);
            if (null != stationByEnterprise) {
                stationIds = stationByEnterprise.stream().map(x -> x.getStationId() + "").collect(Collectors.toList());
            }
        }
        if (UserConstants.LEVEL_THREE.equals(sysUser.getLevelId())) {//油站
            stationIds = new ArrayList<>();
            stationIds.add(sysUser.getStationId() + "");
        }
        if (!SecurityUtils.isAdmin(sysUser.getUserId()) && null != stationIds) {
            stationIds.add("0");//有八条固定的支付方式，油企和油站都是0
        }

        if (StringUtils.isNotBlank(payTypeName)) {
            payType.setPayTypeName(payTypeName);
        }
        payType.setStationIdList(stationIds);
        startPage();
        List<OrderPayTypeResVo> resVos = orderPayTypeMapper.selectOrderPayTypeList(payType);
        PageHelper.clearPage();
        return resVos;
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
}
